<template>
  <el-dialog
    title="用户注册"
    :visible="isShow"
    width="600px"
    :show-close="false"
    class="register"
    @close="closeEvent"
  >
    <template #title>
      <div class="title">用户注册</div>
    </template>
    <div slot="footer" class="footer">
      <el-button @click="closeEvent">取消</el-button>
      <el-button type="primary" @click="sumbit">确定</el-button>
    </div>
    <el-form label-width="100px" :model="form" :rules="rules" ref="form">
      <el-form-item label="头像" class="upload-avatar" prop="avatar">
        <el-upload
          class="avatar-uploader"
          :action="baseUrl + '/uploads'"
          name="image"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            :src="baseUrl + '/' + form.avatar"
            alt=""
            class="avatar"
            v-if="form.avatar"
          />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item prop="username" label="昵称">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item prop="email" label="邮箱">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
      <el-form-item prop="phone" label="手机">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item prop="password" label="密码">
        <el-input v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item prop="code" label="图形码">
        <el-row>
          <el-col :span="15">
            <el-input v-model="form.code"></el-input>
          </el-col>
          <el-col :span="8" :offset="1">
            <img
              class="code-img"
              :src="baseUrl + codeImgUrl"
              alt=""
              @click="refreshCode"
            />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="验证码" prop="rcode">
        <el-row>
          <el-col :span="15">
            <el-input v-model="form.rcode"></el-input>
          </el-col>
          <el-col :span="8" :offset="1">
            <el-button class="btn" :disabled="totalTime != 6" @click="getCode"
              >获取用户验证码<span v-if="totalTime != 6"
                >({{ totalTime }})</span
              ></el-button
            >
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import '@/style/base.css'
import { getCodeApi, registered } from '@/api/registered.js'
export default {
  data () {
    return {
      baseUrl: process.env.VUE_APP_URL,
      codeImgUrl: '/captcha?type=sendsms',
      totalTime: 6,
      isShow: false, // 是否显示对话框,
      form: {
        avatar: '',
        username: '11',
        email: '11@qq.com',
        phone: '',
        password: '12345678',
        code: '',
        rcode: ''
      },
      rules: {
        avatar: [{ required: true, message: '请上传头像', trigger: 'change' }],
        username: [
          { required: true, message: '请输入用户名', trigger: 'change' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              const reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
              if (reg.test(value)) {
                callback()
              } else {
                callback(new Error('请输入正确的邮箱'))
              }
            },
            trigger: 'change'
          }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
              if (reg.test(value)) {
                callback()
              } else {
                callback(new Error('请输入正确的手机号'))
              }
            },
            trigger: 'change'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'change' }
        ],
        code: [{ required: true, message: '请输入图形码', trigger: 'change' }],
        rcode: [{ required: true, message: '请输入验证码', trigger: 'change' }]
      }
    }
  },
  methods: {
    closeEvent () {
      this.$refs.form.resetFields()
      this.form = {
        avatar: '',
        username: '',
        email: '',
        phone: '',
        password: '',
        code: '',
        pcode: ''
      }
      this.isShow = false
    },
    sumbit () {
      this.$refs.form.validate(result => {
        if (result) {
          registered(this.form).then(res => {
            console.log(res)
            this.$message.success('注册成功')
            this.isShow = false
          })
        } else {
          this.$message.error('验证失败')
        }
      })
    },
    handleAvatarSuccess (res) {
      this.form.avatar = res.data.file_path
      // this.res.form.valdateField(['avatar'])
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG,PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 刷新图形码
    refreshCode () {
      this.codeImgUrl = '/captcha?type=sendsms&sdgsg=' + Math.random() * 999
    },

    // 获取手机验证码
    async getCode () {
      let num = 0
      this.$refs.form.validateField(['phone', 'code'], errorMessage => {
        console.log('手机验证', errorMessage)
        if (errorMessage === '') {
          num++
        }
      })
      if (num === 2) {
        this.totalTime--
        const times = setInterval(() => {
          this.totalTime--
          if (this.totalTime <= 0) {
            clearInterval(times)
            this.totalTime = 6
          }
        }, 1000)
      }
      await getCodeApi({
        code: this.form.code,
        phone: this.form.phone
      }).then(res => {
        console.log('res', res)
        const result = res.data.data.captcha
        if (res.data.code === 200) {
          this.$message.success(result)
        } else {
          this.$message.error(res.data.message)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.register {
  .title {
    height: 53px;
    line-height: 53px;
    text-align: center;
    color: #fff;
    background: linear-gradient(to right, #01c4fa, #1294fa);
  }
  ::v-deep .el-dialog__header {
    padding: 0;
  }
  .footer {
    text-align: center;
  }
  .avatar-uploader ::v-deep .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader ::v-deep .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .upload-avatar {
    text-align: center;
  }
  .code-img {
    width: 100%;
    height: 40px;
  }
  .btn {
    width: 100%;
  }
}
</style>
